package com.longer.demo.biz.controller;

import com.longer.demo.biz.controller.model.ItemVO;
import com.longer.demo.biz.service.ItemService;
import com.longer.demo.biz.service.model.ItemModel;
import com.longer.demo.framework.error.BusinessError;
import com.longer.demo.framework.error.BusinessException;
import com.longer.demo.framework.reponse.CommonResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @program: mybatis
 * @description:
 * @author: SunBiaoLong
 * @create: 2019-01-14 13:08
 **/
@RestController
@RequestMapping("/item")
public class ItemController {

	@Autowired
	private ItemService itemService;

	@GetMapping("/id")
	public CommonResponse getItemById(@RequestParam(name = "id") Integer id) throws BusinessException {
		ItemModel itemModel = itemService.getItemById(id);
		if (itemModel == null) {
			throw new BusinessException(BusinessError.PARAMETER_VALIDATION_ERROR, "未找到指定的商品");
		}
		ItemVO itemVO = convertFromItemModel(itemModel);
		return CommonResponse.create(itemVO);
	}


	@PostMapping("/create")
	public CommonResponse createItem(
			@RequestParam(name = "title") String title,
			@RequestParam(name = "price") BigDecimal price,
			@RequestParam(name = "stock") Integer stock,
			@RequestParam(name = "description") String description,
			@RequestParam(name = "sales") Integer sales,
			@RequestParam(name = "imgUrl") String imgUrl) throws BusinessException {
		ItemVO itemVO = new ItemVO();
		itemVO.setTitle(title);
		itemVO.setPrice(price);
		itemVO.setStock(stock);
		itemVO.setDescription(description);
		itemVO.setSales(sales);
		itemVO.setImgUrl(imgUrl);
		ItemModel itemModel = convertFromItemVO(itemVO);
		ItemModel savedItemModel = itemService.createItem(itemModel);
		return CommonResponse.create(savedItemModel);
	}

	@GetMapping("/list")
	public CommonResponse getItemList() {
		List<ItemModel> itemModelList = itemService.getItemList();
		return CommonResponse.create(itemModelList.stream().map(this::convertFromItemModel));
	}

	private ItemVO convertFromItemModel(ItemModel itemModel) {
		if (itemModel == null) {
			return null;
		}
		ItemVO itemVO = new ItemVO();
		BeanUtils.copyProperties(itemModel, itemVO);
		return itemVO;
	}

	private ItemModel convertFromItemVO(ItemVO itemVO) {
		if (itemVO == null) {
			return null;
		}
		ItemModel itemModel = new ItemModel();
		BeanUtils.copyProperties(itemVO, itemModel);
		return itemModel;
	}

}
